<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>使用Promise封装Ajax</title>
</head>
<body>
  
</body>

<script type="text/javascript">

  const getJSON = function (url) {
    return new Promise((resolvoe, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json'
      xhr.setRequestHeader('Accept', 'application/json')
      xhr.send()

      function handler() {
        console.log(this);
        if (this.readyState === 4) {
          if (this.status === 200) {
            resolvoe(this.response.data)
          } else {
            reject(this.response.error)
          }
        }
        
      }
    })
  }

  let requestUrl = 'http://localhost:8001/user/get'
  let requestUrl1 = 'http://localhost:8001/user/get1'
  console.log('getJson', getJSON(requestUrl));
  getJSON(requestUrl).then((data) => {
    console.log(data);
  }, (error) => {
    console.log(error);
  })

  getJSON(requestUrl1)
  .then((data) => {
    console.log(data);
  }).catch(err => {
    console.log(err);
  })

  getJSON(requestUrl1)
  .then((data) => {
    console.log(data);
  }).then(null, err => {
    console.log(err);
  })



</script>
</html>